package com.example.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.entity.Img;
import com.example.entity.User;
import com.example.entity.param.JWTParam;
import com.example.interceptor.TokenNotValidation;
import com.example.response.R;
import com.example.service.ImgService;
import com.example.service.LoginService;
import com.example.service.UserService;
import com.example.utils.ImgUtil;
import com.example.utils.JwtUtil;
import com.example.utils.MD5Util;

import com.example.utils.NoteUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    LoginService loginService;

    @Autowired
    ImgUtil imgUtil;

    @Autowired
    ImgService imgService;

    @Autowired
    UserService userService;

    @Autowired
    @Qualifier("redisTemplateM")
    RedisTemplate redisTemplateM;

    /**
     * 密码登录
     *
     * @param str
     * @return
     */
    @TokenNotValidation
    @PostMapping("/login")
    public HashMap<String, String> login(@RequestBody String str) {
        JSONObject strj = JSON.parseObject(str);
        return loginService.getToken(strj.getString("phone"), strj.getString("password"));
    }

    //通过手机号验证码获取登陆
    @TokenNotValidation
    @PostMapping("/getTokenByPhoneCode")
    public Map<String, String> phoneCode(@RequestBody String str) {
        Map<String, String> map = new HashMap<String, String>();//初始化一个hashmap用于存放键值对数据
        JSONObject strj = new JSONObject();
        strj = JSON.parseObject(str);
        Object code = redisTemplateM.opsForValue().get(strj.getString("phone"));
        if (strj.getString("code").equals(code.toString())) {
            return loginService.phoneCode(strj.getString("phone"));
        }
        map.put("codeInfo", "验证码有问题或者已过期");
        return map;
    }

    //发送验证码存在session
    @TokenNotValidation
    @PostMapping("loginwithcode")
    public R code(@RequestBody String str) {
        JSONObject strj = JSON.parseObject(str);
        NoteUtil noteUtil = new NoteUtil();
        String code = noteUtil.sendSms(strj.getString("phone"));
        if (code.equals("结果没出来") || code.equals("响应码错误") || code.equals("解析错误") || code.equals("网络IO错误")) {
            return R.fail(500, "失败");
        }
        redisTemplateM.opsForValue().set(strj.getString("phone"), code, 60, TimeUnit.SECONDS);
        return R.success();
    }


    /**
     * 持续更新获取token
     *
     * @param request
     * @return
     */
    @TokenNotValidation
    @GetMapping("/reGetToken")
    public HashMap<String, String> reGetToken(HttpServletRequest request) {
        HashMap<String, String> map = new HashMap<>();
        String token = request.getHeader("Authorization");
        JWTParam param = new JWTParam();
        param.setUserid(JwtUtil.getUserId(token.substring(7)));
        param.setPhone(JwtUtil.getPhone(token.substring(7)));
        param.setRole(JwtUtil.getRole(token.substring(7)));
        param.setAuth(JwtUtil.getAuth(token.substring(7)));
        String sign = JwtUtil.sign(param);
        map.put("info", "success");
        map.put("token", sign);
        return map;
    }

    /**
     * 注册
     *
     * @param user
     * @return
     */
    @TokenNotValidation
    @PostMapping("/register")
    public R register(@RequestBody User user) {
        Object code = redisTemplateM.opsForValue().get(user.getPhone());

        if (code.equals(user.getCode())) {
            Boolean aBoolean = loginService.checkIsRegisterByPhone(user.getPhone());
            if (aBoolean) {
                return R.fail(400, "对不起，您的手机号已经注册！！");
            }
            String password = user.getPassword();
            password = MD5Util.getMD5(password);
            user.setPassword(password);
            user.setRoleId(2);
            user.setStatus(1);
            user.setCreatDate(new Date());
            int userid = loginService.register(user);
            return R.success(userid);
        } else {
            return R.fail(400, "验证码出错");
        }
    }

    /**
     * 上传图片
     *
     * @param file
     * @return
     */
    @TokenNotValidation
    @PostMapping("/uploadImg")
    public int uploadImg(MultipartFile file) {
        String logopath = imgUtil.upload(file);
        Img img = new Img();
        img.setCreatdate(new Date());
        img.setPath(logopath);
        return imgService.insert(img);
    }

    /**
     * 获取自身信息
     *
     * @param request
     * @return
     */
    @TokenNotValidation
    @GetMapping("/getUserHimself")
    public User getUserHimself(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        Integer userid = JwtUtil.getUserId(token.substring(7));
        return userService.selectByPrimaryKey(userid);
    }

}
